<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="batchName">
              <el-input
                v-model="queryParams.batchName"
                :placeholder="$t('批次名称')"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 批次号 -->
            <el-form-item prop="batchNo">
              <el-input
                v-model="queryParams.batchNo"
                :placeholder="$t('批次号')"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 是否出运 -->
            <el-form-item prop="isTransport">
              <el-select
                :placeholder="$t('是否出运')"
                @change="handleQuery"
                style="width: 100%"
                v-model="queryParams.isTransport"
              >
                <el-option :label="$t('是')" :value="1" />
                <el-option :label="$t('否')" :value="0" />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addBatchListData"
          v-hasPermi="['distribution:batch:add']"
        >
          <!-- 创建批次 -->
          {{ $t('创建批次') }}
        </el-button>
      </template>
    </PageSearch>
    <el-table
      v-loading="loading"
      ref="MainTableRef"
      :data="batchList"
      @expand-change="expandChange"
      :row-key="(row) => row.id"
      :expand-row-keys="expandRowKeys"
    >
      <el-table-column show-overflow-tooltip type="expand">
        <template slot-scope="scope">
          <div v-loading="tabelFlag"></div>
          <div style="display: flex" v-if="scope.row.children" :style="{ '--sku-width': skuWidth }">
            <table>
              <div style="display: none">{{ tabelFlag }}</div>
              <tr class="header">
                <td>
                  <!-- 箱子号码 -->
                  <div style="width: 100px">
                    {{ $t('箱子号码') }}
                  </div>
                </td>
                <td>
                  <!-- 状态 -->
                  <div style="width: 100px">
                    {{ $t('状态') }}
                  </div>
                </td>
                <td>
                  <!-- 产品总数量 -->
                  <div style="width: 100px">
                    {{ $t('产品总数量') }}
                  </div>
                </td>
                <td>
                  <!-- 箱子总重量 -->
                  <div style="width: 100px">{{ $t('箱子总重量') }}(KG)</div>
                </td>
                <td>
                  <!-- 真实重量 -->
                  <div style="width: 100px">{{ $t('真实重量') }}(KG)</div>
                </td>
                <!-- <td>
                  <!~~ 库位号 ~~>
                  <div style="width: 100px">
                    {{ $t("库位号") }}
                  </div>
                </td>-->
              </tr>
              <tr v-for="(item, index) in scope.row.children" :key="index">
                <td>
                  <div style="width: 100px">
                    <el-button type="text" style="height: 32px" @click="completeBatch(item)">
                      {{ item.boxNo ? item.boxNo : '-' }}
                    </el-button>
                  </div>
                </td>
                <td>
                  <div style="width: 100px">
                    <!-- {{ item.completeStatus == 1 ? "完成" : "未完成" }} -->
                    {{ item.completeStatus == 1 ? $t('完成') : $t('未完成') }}
                  </div>
                </td>
                <td>
                  <div style="width: 100px">
                    {{ item.boxTotalCount ? item.boxTotalCount : '-' }}
                  </div>
                </td>
                <td>
                  <div style="width: 100px">
                    {{ item.boxTotalWeight ? item.boxTotalWeight : '-' }}
                  </div>
                </td>
                <td>
                  <div>
                    {{ item.truthWeight ? item.truthWeight : '-' }}
                  </div>
                </td>
                <td>
                  <div style="width: 100px">
                    {{ item.spNo ? item.spNo : '-' }}
                  </div>
                </td>
                <div style="width: var(--sku-width); overflow: auto">
                  <td style="width: 200px" v-for="(item, index) in item.batchBoxSkuList" :key="index">
                    <div class="ImageList">
                      <div style="width: 80px">{{ item.skuNo }}</div>
                      <div style="width: 30px">
                        <el-image
                          class="goods-img-mini"
                          :key="Math.random()"
                          v-hover="item.imgUrl"
                          :src="item.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
                        />
                      </div>
                      <div style="width: 30px">{{ item.num }}</div>
                    </div>
                  </td>
                </div>
              </tr>
              <tr v-if="scope.row.children.length == 0">
                <td colspan="5">
                  <div>
                    <!-- 暂无数据 -->
                    {{ $t('暂无数据') }}
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </template>
      </el-table-column>

      <!-- 批次名称 -->
      <el-table-column show-overflow-tooltip :label="$t('批次名称')" align="center" prop="batchName" />
      <!-- 生成装箱单 -->
      <el-table-column show-overflow-tooltip :label="$t('生成装箱单')" align="center" prop="batchNo" />
      <!-- 是否出运 -->
      <el-table-column show-overflow-tooltip :label="$t('是否出运')" align="center" prop="isTransport">
        <template slot-scope="{ row }">
          <!-- {{ row.isTransport == 1 ? "是" : "否" }} -->
          <span v-if="row.isTransport == 1" style="color: green">
            {{ $t('是') }}
          </span>
          <span v-else style="color: red">
            {{ $t('否') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip :label="$t('头程')" align="center" prop="headPathExpress">
        <template #default="{ row }">
          <div style="font-size: 12px; line-height: 16px">
            <div>{{ row.headPathExpress }}</div>
            <el-link :href="row.headPathNet" target="_blank">{{ row.headPathNet || '-' }}</el-link>
            <div>{{ row.headPathExpressNo }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip :label="$t('中程')" align="center" prop="centrePathExpress">
        <template #default="{ row }">
          <div style="font-size: 12px; line-height: 16px">
            <div>{{ row.centrePathExpress }}</div>
            <el-link :href="row.centrePathNet" target="_blank">{{ row.centrePathNet || '-' }}</el-link>
            <div>{{ row.centrePathExpressNo }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip :label="$t('尾程')" align="center" prop="tailPathExpress">
        <template #default="{ row }">
          <div style="font-size: 12px; line-height: 16px">
            <div>{{ row.tailPathExpress }}</div>
            <el-link :href="row.tailPathNet" target="_blank">{{ row.tailPathNet || '-' }}</el-link>
            <div>{{ row.tailPathExpressNo }}</div>
          </div>
        </template>
      </el-table-column>
      <!-- 创建时间 -->
      <el-table-column show-overflow-tooltip :label="$t('创建时间')" align="center" prop="createTime" />
      <!-- 备注 -->
      <el-table-column show-overflow-tooltip :label="$t('备注')" align="center" prop="remark" />
      <!-- 操作 -->
      <el-table-column show-overflow-tooltip :label="$t('操作')" align="center">
        <template slot-scope="scope">
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button type="text" icon="el-icon-d-arrow-right">
              {{ $t('更多') }}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <!-- 报关单导出 -->
              <el-dropdown-item
                v-hasPermi="['distribution:batch:boxSkuCustomsClearanceExport']"
                command="boxSkuCustomsClearanceExport"
              >
                {{ $t('报关单导出') }}
              </el-dropdown-item>
              <!-- 导出装箱 -->
              <el-dropdown-item
                v-hasPermi="['distribution:batch:boxSkuExportByWarehouse']"
                command="boxSkuExportByWarehouse"
              >
                {{ $t('导出装箱') }}
              </el-dropdown-item>
              <!-- 导出装箱(有价格) -->
              <el-dropdown-item
                v-hasPermi="['distribution:batch:boxSkuExportByPlatform']"
                command="boxSkuExportByPlatform"
              >
                {{ $t('导出装箱(有价格)') }}
              </el-dropdown-item>
              <!-- 追加箱子 装箱列表已出运后不能再追加箱子-->
              <el-dropdown-item :disabled="scope.row.isTransport == 1" command="appendBox">
                {{ $t('追加箱子') }}
              </el-dropdown-item>
              <!-- 出运 -->
              <el-dropdown-item
                command="completeTransportation"
                v-hasPermi="['distribution:batch:completeTransportation']"
                :disabled="scope.row.isTransport !== 0"
              >
                {{ scope.row.isTransport == 0 ? $t('出运') : $t('已出运') }}
              </el-dropdown-item>
              <!-- <el-dropdown-item command="updateBatch" v-hasPermi="['distribution:batch:updateBatch']">
                {{ $t('编辑') }}
              </el-dropdown-item> -->
              <el-dropdown-item command="editBatch" v-hasPermi="['distribution:batch:updateBatch']">
                {{ $t('编辑批次') }}
              </el-dropdown-item>
              <el-dropdown-item command="editLogistics" v-hasPermi="['distribution:batch:getBatchExpressListById']">
                {{ $t('编辑物流') }}
              </el-dropdown-item>

              <el-dropdown-item
                command="useRecord"
                v-hasPermi="['distribution:skuConsumable:getBatchSkuConsumableRecords']"
              >
                {{ $t('耗材使用情况（扣减记录）') }}
              </el-dropdown-item>
              <el-dropdown-item command="deleteBatch" v-hasPermi="['distribution:batch:deleteBatchById']">
                {{ $t('删除批次') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 追加箱子 -->
    <el-dialog
      :before-close="cancelBox"
      destroy-on-close
      :title="$t('追加箱子')"
      :visible.sync="boxDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="formBox" :model="formBox" :rules="rulesBox" label-width="120px">
        <!-- 批次名称 -->
        <el-form-item :label="$t('批次名称')" prop="batchName">
          <el-input v-model="formBox.batchName" disabled :placeholder="$t('请输入')" />
        </el-form-item>
        <el-form-item :label="$t('当前箱子数量')" prop="curentBoxNum">
          <el-input v-model="formBox.curentBoxNum" disabled :placeholder="$t('请输入')" />
        </el-form-item>
        <el-form-item :label="$t('追加数量')" prop="boxNum">
          <el-input v-model="formBox.boxNum" :placeholder="$t('请输入')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitboxForm">
          <!-- 确 定 -->
          {{ $t('确定') }}
        </el-button>
        <el-button @click="cancelBox">
          <!-- 取 消 -->
          {{ $t('取消') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 创建批次 -->
    <el-dialog
      :before-close="cancelBatch"
      :title="$t('创建批次')"
      :visible.sync="BatchDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="formBatch" :model="formBatch" :rules="rulesBatch" label-width="120px">
        <!-- 批次名称 -->
        <el-form-item :label="$t('批次名称')" prop="batchName">
          <el-input v-model="formBatch.batchName" :placeholder="$t('请输入')" />
        </el-form-item>
        <!-- 箱子数量 -->
        <el-form-item :label="$t('箱子数量')" prop="boxNum">
          <el-input v-model="formBatch.boxNum" :placeholder="$t('请输入')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitBatchForm">
          <!-- 确 定 -->
          {{ $t('确定') }}
        </el-button>
        <el-button @click="cancelBatch">
          <!-- 取 消 -->
          {{ $t('取消') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- sku图片详情列表 -->
    <el-dialog
      :before-close="cancelSku"
      destroy-on-close
      :title="$t('详情')"
      :visible.sync="SkuDialog"
      width="900px"
      append-to-body
    >
      <div>
        <el-row>
          <el-col :span="6">
            <b>{{ $t('箱子号码') }}:{{ SkuDialogData.boxNo }}</b>
          </el-col>
          <el-col :span="6">
            <!-- 完成状态 1-已完成 2-未完成 -->
            <b>
              {{ $t('状态') }}:
              <span v-if="SkuDialogData.completeStatus == 1" style="color: #409eff">{{ $t('已完成') }}</span>
              <span v-if="SkuDialogData.completeStatus == 2" style="color: red">{{ $t('未完成') }}</span>
            </b>
          </el-col>
          <el-col :span="6">
            <b>{{ $t('箱子总重量') }}:{{ SkuDialogData.boxTotalWeight }}kg</b>
          </el-col>
          <el-col :span="6">
            <b>{{ $t('真实重量') }}:{{ SkuDialogData.truthWeight }}kg</b>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row :gutter="10" class="mb8" style="display: flex; align-items: center">
          <el-col :span="1.5" v-hasPermi="['distribution:batch:edit']">
            {{ $t('完成箱子') }}
            <el-switch
              v-model="SkuDialogData.completeStatus"
              :inactive-value="2"
              :active-value="1"
              @change="handleStatusChange"
            >
            </el-switch>
          </el-col>

          <el-col :span="1.5">
            <el-popconfirm @confirm="deleteBatchBoxList" :title="$t('确认删除?')"> </el-popconfirm>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              size="mini"
              v-hasPermi="['distribution:batch:scanQrCode']"
              @click="changeBoxTruthWeight"
            >
              {{ $t('修改箱子真实重量') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <div style="display: flex">
              <el-input
                clearable
                class="parcel"
                @change="debounce"
                size="mini"
                v-model="addContainerSerialForm.skuSerializable"
                :placeholder="$t('请扫描序列号')"
              ></el-input>
              <el-button
                class="btnParcel"
                @click="debounce"
                v-hasPermi="['distribution:batch:deleteBoxSkuSerializable']"
                type="primary"
                size="mini"
              >
                {{ $t('添加') }}
              </el-button>
            </div>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              v-hasPermi="['distribution:batch:convertBoxNo']"
              @click="handleSwitchBox"
            >
              {{ $t('箱号互换') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              :disabled="batchBoxSkuList.length !== 0"
              plain
              size="mini"
              v-hasPermi="['distribution:batch:deleteBox']"
              @click="handleDeleteBox"
            >
              {{ $t('删除箱子') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- 完成箱子不能操作 -->
            <el-button
              type="info"
              :disabled="SkuDialogData.completeStatus == 1"
              plain
              size="mini"
              v-hasPermi="['distribution:batch:cancelSer']"
              @click="handleScanCancelBox"
            >
              {{ $t('扫码取消装箱') }}
            </el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" max-height="400" ref="TableRef" :data="batchBoxSkuList">
          <!-- 供应商 -->
          <el-table-column show-overflow-tooltip :label="$t('供应商')" prop="distrName" align="center" />
          <!-- sku编号 -->
          <el-table-column show-overflow-tooltip :label="$t('sku编号')" prop="skuNo" align="center" />
          <!-- 图片 -->
          <el-table-column prop="imgUrl" :label="$t('图片')" align="center">
            <template slot-scope="scope">
              <el-image
                fit="contain"
                style="width: 50px; height: 50px"
                :key="Math.random()"
                v-hover="scope.row.imgUrl"
                :src="scope.row.imgUrl"
              />
            </template>
          </el-table-column>
          <!-- 数量 -->
          <el-table-column show-overflow-tooltip :label="$t('数量')" prop="num" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="showContainerSerialNumber(scope.row)">{{ scope.row.num }}</el-button>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column show-overflow-tooltip :label="$t('操作')" align="center">
            <div slot-scope="scope">
              <el-button
                v-hasPermi="['distribution:batch:exchangeBox']"
                type="text"
                @click="handleSkuChangeBox(scope.row)"
                >{{ $t('换箱') }}</el-button
              >
              <!-- 删除限制：1.只能从最后一个箱子开始删除，不能从中间删除，只能删除空箱子 -->
              <el-button
                type="text"
                v-hasPermi="['distribution:batch:deleteBoxSku']"
                @click="deleteListData(scope.row)"
              >
                {{ $t('删除') }}
              </el-button>
            </div>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSku">
          <!-- 关 闭 -->
          {{ $t('关闭') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 装箱序列号明细 -->
    <el-dialog
      :before-close="isshowContains"
      destroy-on-close
      :title="$t('装箱序列号明细')"
      :visible.sync="ContainerSerialNumberFlage"
      width="900px"
      append-to-body
    >
      <div>
        <el-table max-height="400" ref="TableRef" :data="ContainerList">
          <!-- 序号 -->
          <el-table-column show-overflow-tooltip width="80" :label="$t('序号')" type="index" align="center" />
          <!-- 序列号 -->
          <el-table-column show-overflow-tooltip :label="$t('序列号')" prop="skuSerializable" align="center" />
          <!-- 操作 -->
          <el-table-column show-overflow-tooltip :label="$t('操作')" align="center">
            <div slot-scope="scope">
              <!-- 确认删除 -->
              <el-popconfirm
                v-hasPermi="['distribution:batch:deleteBoxSkuSerializable']"
                @confirm="BoxSkuSerializable(scope.row)"
                :title="$t('确定删除?')"
              >
                <el-link type="danger" slot="reference">
                  <!-- 删除 -->
                  {{ $t('删除') }}
                </el-link>
              </el-popconfirm>
            </div>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isshowContains">
          <!-- 关 闭 -->
          {{ $t('关闭') }}
        </el-button>
      </div>
    </el-dialog>
    <UseRecord :show.sync="useRecord.show" @getList="getList" :formData="useRecord.formData" />
    <SwitchBox
      :show.sync="switchBox.show"
      @getList="
        () => {
          SkuDialog = false
          curentData()
        }
      "
      :formData="switchBox.formData"
    />
    <!-- 编辑批次 -->
    <EditBatch :show.sync="editBatch.show" @getList="getList" :formData="editBatch.formData" />
    <!-- 编辑物流 -->
    <EditLogistics :show.sync="editLogistics.show" @getList="getList" :formData="editLogistics.formData" />
    <!-- sku 换箱 -->
    <SkuChangeBox
      :show.sync="skuChangeBox.show"
      :formData="skuChangeBox.formData"
      @getList="
        () => {
          querygetBoxSkuList()
          getList()
        }
      "
    />
    <ScanCancelBox
      :show.sync="scanCancelBox.show"
      :formData="scanCancelBox.formData"
      @getList="
        () => {
          querygetBoxSkuList()
        }
      "
    />
  </div>
</template>

<script>
import {
  appendBox,
  completeBatchBox,
  completeTransportation,
  createBatch,
  delBatch,
  deleteBatchBox,
  deleteBatchBoxSku,
  deleteBatchById,
  deleteBox,
  deleteBoxSkuSerializable,
  getBatchBoxSkuListByBatchId,
  getBatchBoxSkuSerializableList,
  getBatchDetails,
  getBoxSkuList,
  listBatch,
  scanQrCode,
  updateBoxTruthWeight,
} from '@/api/purchasingManage/batch'
import _ from 'lodash' // 导入lodash库
import EditBatch from './components/editBatch.vue'
import EditLogistics from './components/editLogistics.vue'
import SwitchBox from './components/switchBox.vue'
import UseRecord from './components/useRecord.vue'
import SkuChangeBox from './components/skuChangeBox.vue'
import ScanCancelBox from './components/scanCancelBox.vue'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'Batch',
  components: { EditBatch, EditLogistics, UseRecord, SwitchBox, SkuChangeBox, ScanCancelBox },
  data() {
    return {
      scanCancelBox: {
        show: false,
        formData: {},
      },
      skuChangeBox: {
        show: false,
        formData: {},
      },
      skuWidth: '',
      /**编辑批次 */
      editBatch: {
        show: false,
        formData: {},
      },
      /**编辑物流 */
      editLogistics: {
        show: false,
        formData: {},
      },
      switchBox: {
        show: false,
        formData: {},
      },

      useRecord: {
        show: false,
        formData: {},
      },
      /**表格展开项key */
      expandRowKeys: [],
      /**表格展开项 */
      expandRows: [],
      debounceClick: _.debounce(this.submitContainerSerialForm, 500), // 500 毫秒的防抖延迟
      /**序列号新增表单 */
      addContainerSerialForm: {
        skuSerializable: '',
      },
      /**装箱序列号列表 */
      ContainerList: [],
      /**装箱序列号 */
      ContainerSerialNumberFlage: false,
      // 当前点击的数据
      curentClickData: {},
      batchBoxSkuList: [],
      /**loading */
      tabelFlag: false,
      SkuDialogData: {},
      SkuDialog: false,
      BatchDialog: false,
      formBatch: {
        boxNum: '',
        batchName: '',
      },
      // 批次列表详情
      curentBoxInforData: {},
      // 追加箱子
      formBox: {
        curentBoxNum: '',
        boxNum: 1,
        batchName: '',
      },
      // 追加箱子弹框
      boxDialog: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 批次表格数据
      batchList: [
        // {
        //   batchName: "批次名称",
        //   batchNo: "装箱单号码",
        //   children: [
        //     {
        //       label: "212",
        //       value: "212",
        //       children: [
        //         {
        //           label: "222",
        //           value: "22223343",
        //         },
        //       ],
        //     },
        //     {
        //       label: "212",
        //       value: "212",
        //     },
        //   ],
        // },
      ],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchName: undefined,
        batchNo: undefined,
        isTransport: undefined,
      },
      // 表单参数
      form: {},
      rulesBox: {
        boxNum: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
      },
      rulesBatch: {
        batchName: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        boxNum: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
      },
      // 表单校验
      rules: {
        id: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        batchName: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        batchNo: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        isTransport: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        remark: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
      },
    }
  },
  mounted() {
    this.setSkuWidth()
    window.addEventListener('resize', () => this.setSkuWidth())
  },
  created() {
    this.getList()
  },
  methods: {
    handleScanCancelBox() {
      this.scanCancelBox.formData = { ...this.SkuDialogData }
      this.scanCancelBox.show = true
    },
    handleSkuChangeBox(row) {
      this.skuChangeBox.formData = JSON.parse(JSON.stringify({ ...row, batchId: this.SkuDialogData.batchId }))
      this.skuChangeBox.show = true
    },
    setSkuWidth() {
      const _width = 640
      let menuWidth
      if (this.$store.state.app.sidebar.opened) {
        menuWidth = 200
        this.skuWidth = window.innerWidth - _width - menuWidth
      } else {
        menuWidth = 54
        this.skuWidth = window.innerWidth - _width - menuWidth
      }
      this.skuWidth += 'px'
    },
    handleSwitchBox() {
      this.switchBox.formData = this.SkuDialogData
      this.switchBox.show = true
    },
    handleDeleteBox() {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        const boxId = this.SkuDialogData.id
        deleteBox(boxId).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.SkuDialog = false
            this.$message({ type: 'success', message: msg })
            this.curentData()
          }
        })
      })
    },
    // type，1-已完成 2-未完成
    handleStatusChange(e) {
      const data = {
        boxId: this.SkuDialogData.id,
        type: this.SkuDialogData.completeStatus,
      }
      completeBatchBox(data)
        .then((res) => {
          const { code, msg } = res
          this.$message({ type: 'success', message: msg })
          this.cancelSku()
          this.curentData()
        })
        .catch(() => {
          if (e == 1) {
            this.SkuDialogData.completeStatus = 2
          } else {
            this.SkuDialogData.completeStatus = 1
          }
        })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'boxSkuCustomsClearanceExport' /**报关单导出 */:
          this.handleBoxSkuCustomsClearanceExport(row)
          break
        case 'boxSkuExportByWarehouse' /**导出装箱 */:
          this.handleExportBoxList(row)
          break
        case 'boxSkuExportByPlatform' /**导出装箱(有价格) */:
          this.handleExport(row)
          break
        case 'appendBox' /**追加箱子 */:
          this.addBatchList(row)
          break
        case 'completeTransportation' /**出运 */:
          this.$confirm(this.$t('确定出运?'), this.$t('提示'), {
            type: 'warning',
          }).then(() => {
            this.isTransport(row)
          })
          break
        case 'editBatch' /**编辑批次 */:
          this.editBatch.formData = row
          this.editBatch.show = true
          break
        case 'editLogistics' /**编辑物流 */:
          this.editLogistics.formData = row
          this.editLogistics.show = true
          break
        case 'useRecord' /**耗材使用情况（扣减记录） */:
          this.useRecord.formData = row
          this.useRecord.show = true
          break
        case 'deleteBatch' /**删除批次 */:
          this.$confirm(this.$t('确认删除批次?'), this.$t('提示'), {
            type: 'warning',
          }).then(() => {
            deleteBatchById(row.id).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })
                this.getList()
              }
            })
          })
          break
        default:
          break
      }
    },
    BoxSkuSerializable(row) {
      deleteBoxSkuSerializable({ skuSerializableId: row.id }).then((res) => {
        this.$message({ type: 'success', message: res.msg })
      })
    },
    // 带有防抖的点击事件处理函数
    debounce: _.debounce(function () {
      this.submitContainerSerialForm() // 调用实际的点击事件处理函数
    }, 500), // 500 毫秒的防抖延迟
    /**添加序列号 */
    submitContainerSerialForm() {
      var utterance = new SpeechSynthesisUtterance()
      utterance.rate = 2
      this.addContainerSerialForm.batchBoxId = this.SkuDialogData.id
      if (this.addContainerSerialForm.skuSerializable != '') {
        scanQrCode(this.addContainerSerialForm)
          .then((res) => {
            utterance.text = '成功'
            window.speechSynthesis.speak(utterance)
            this.addContainerSerialForm.skuSerializable = ''
            this.$message({ type: 'success', message: res.msg })

            this.querygetBoxSkuList()
            this.handleExpand()
          })
          .catch((res) => {
            utterance.text = '失败'
            window.speechSynthesis.speak(utterance)
          })
      }
    },
    isshowContains() {
      this.ContainerSerialNumberFlage = !this.ContainerSerialNumberFlage
    },
    /**装箱序列号列表显示 */
    showContainerSerialNumber(row) {
      this.isshowContains()
      getBatchBoxSkuSerializableList({ batchBoxSkuId: row.id }).then((res) => {
        this.ContainerList = res.data
      })
    },
    // 修改箱子重量弹框
    changeBoxTruthWeight() {
      let data = this.SkuDialogData

      this.$prompt(this.$t('真实重量'), this.$t('编辑'), {
        // confirmButtonText: "确定",
        // cancelButtonText: "取消",
        inputPattern: /^(0|[1-9]\d*)(\.\d+)?$/,
        // inputErrorMessage: "箱子真实重量必须大于零可以是小数",
        inputErrorMessage: this.$t('请输入'),
      })
        .then(({ value }) => {
          updateBoxTruthWeight({ boxId: data.id, truthWeight: value }).then((res) => {
            this.$message({
              type: 'success',
              message: res.msg,
            })
            this.SkuDialogData.truthWeight = res.data
            this.curentData()
          })
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "取消输入",
          // });
        })
    },
    // 查询sku列表
    querygetBoxSkuList() {
      getBoxSkuList({ boxId: this.SkuDialogData.id }).then((res) => {
        this.batchBoxSkuList = res.data
      })
    },
    deleteBatchBoxList() {
      deleteBatchBox({ id: this.SkuDialogData.id }).then((res) => {
        const { code, data, msg } = res
        if ((res.code = 200)) {
          this.$message({ type: 'success', message: msg })

          this.curentData()
          this.cancelSku()
        }
      })
    },
    // 删除箱子里sku
    deleteListData(value) {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        deleteBatchBoxSku({ id: value.id }).then((res) => {
          const { code, data, msg } = res
          if ((res.code = 200)) {
            this.$message({ type: 'success', message: msg })
            this.querygetBoxSkuList()
            this.getList()
          }
        })
      })
    },

    cancelSku() {
      this.SkuDialog = !this.SkuDialog
      this.addContainerSerialForm = {}
      if (this.SkuDialog) {
        this.querygetBoxSkuList()
      } else {
      }
    },
    submitSkuForm() {},
    // 完成箱子
    accomplishBox() {
      if (this.SkuDialogData.completeStatus == 2) {
        completeBatchBox({ boxId: this.SkuDialogData.id }).then((res) => {
          const { code, data, msg } = res
          this.$message({ type: 'success', message: msg })

          this.cancelSku()
          this.curentData()
        })
      }
    },
    completeBatch(value) {
      // console.log(`value ==>`, JSON.parse(JSON.stringify(value)))
      this.SkuDialogData = value
      this.cancelSku()
    },
    isTransport(value) {
      if (value.isTransport == 0) {
        completeTransportation({ batchId: value.id }).then((res) => {
          const { code, data, msg } = res
          this.$message({ type: 'success', message: msg })

          this.getList()
        })
      }
    },
    cancelBatch() {
      this.$refs.formBatch.resetFields()
      this.BatchDialog = !this.BatchDialog
    },

    submitBatchForm() {
      this.$refs.formBatch.validate((valid) => {
        if (valid) {
          createBatch(this.formBatch).then((res) => {
            const { code, data, msg } = res
            this.$message({ type: 'success', message: msg })

            this.getList()
            this.cancelBatch()
          })
        }
      })
    },
    // 追加批次
    addBatchListData() {
      this.BatchDialog = !this.BatchDialog
    },

    cancelBox() {
      this.$refs.formBox.resetFields()
      this.boxDialog = !this.boxDialog
    },
    // 提交追加箱子
    submitboxForm() {
      this.$refs.formBox.validate((valid) => {
        if (valid) {
          appendBox(this.formBox).then((res) => {
            const { code, data, msg } = res
            this.$message({ type: 'success', message: msg })

            this.curentData()
            this.boxDialog = !this.boxDialog
            this.formBox.boxNum = ''
          })
        }
      })
    },
    // 追加箱子
    addBatchList(value) {
      this.formBox = value
      this.expandChange(value)
      this.boxDialog = !this.boxDialog
      getBatchDetails({
        id: value.id,
      }).then((res) => {
        let oldData = JSON.parse(JSON.stringify(res.data))
        this.formBox.curentBoxNum = oldData.boxNum
        this.$forceUpdate()
      })
    },

    /**处理展开项数据 */
    handleExpandRows(row) {
      const index = this.expandRows.findIndex((i) => i.id == row.id)
      if (index == -1) {
        this.expandRows.push(JSON.parse(JSON.stringify(row)))
      } else {
        this.expandRows.splice(index, 1)
      }
      // console.log(` ==>`, JSON.parse(JSON.stringify(this.expandRows)));
    },
    /**展开  展开项 */
    async handleExpand() {
      for (const item of this.expandRows) {
        const { code, data } = await getBatchBoxSkuListByBatchId({
          batchId: item.id,
        })
        // data.forEach((i) => (i.boxTotalCount = Math.random().toFixed(4)));
        if (code === 200) {
          // console.log(`data ==>`, data);
          this.batchList.map((_, index) => {
            if (_.id == item.id) {
              this.tabelFlag = false
              _.children = data
            }
          })
        }
      }
      this.expandRowKeys = this.expandRows.map((i) => i.id)
    },
    // 用户点击展开
    expandChange(row, expandedRows) {
      // console.log(` ==>`, JSON.parse(JSON.stringify({ row, expandedRows })))
      if (expandedRows) this.expandRowKeys = expandedRows.map((i) => i.id)
      this.handleExpandRows(row)
      // 更新当前数据
      this.curentClickData = row
      this.curentData()
    },

    curentData() {
      this.tabelFlag = true
      getBatchBoxSkuListByBatchId({ batchId: this.curentClickData.id }).then((res) => {
        this.$nextTick(() => {
          this.batchList.map((item, index) => {
            if (item.id == this.curentClickData.id) {
              this.tabelFlag = false
              item.children = res.data
            }
          })
        })
      })
    },
    /** 查询批次列表 */
    getList() {
      // MainTableRef
      this.$refs['MainTableRef']?.toggleAllSelection(false)
      this.expandRowKeys = []
      this.loading = false
      listBatch(this.queryParams).then((response) => {
        this.batchList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        batchName: undefined,
        batchNo: undefined,
        isTransport: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm(this.$t('确定删除?'))
        .then(() => {
          this.loading = true
          return delBatch(ids)
        })
        .then((res) => {
          const { code, data, msg } = res
          this.$message({ type: 'success', message: msg })

          this.loading = false
          this.curentData()
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },
    handleBoxSkuCustomsClearanceExport(data) {
      this.download(
        'distribution/batch/boxSkuCustomsClearanceExport',
        { batchId: data.id },
        `batch_${new Date().getTime()}.xlsx`,
        { timeout: 60 * 1000 * 20 /**20分钟 */ },
      )
    },
    handleExportBoxList(data) {
      this.download(
        'distribution/batch/boxSkuExportByWarehouseAdmin',
        { batchId: data.id },
        `batch_${new Date().getTime()}.xlsx`,
        { timeout: 60 * 1000 * 20 /**20分钟 */ },
      )
    },

    /** 导出按钮操作 */
    handleExport(data) {
      this.download('distribution/batch/boxSkuExport', { batchId: data.id }, `batch_${new Date().getTime()}.xlsx`, {
        timeout: 60 * 1000 * 20 /**20分钟 */,
      })
    },
  },
}
</script>
<style lang="scss" scoped>
table {
  border-collapse: collapse;
}

tr {
  width: 100%;
  background-color: rgb(243, 243, 243);
}

tr:hover {
  background: white !important;
}

td {
  padding: 0 !important;
  margin: 0 !important;
  word-break: break-word;
  color: #515a6e;
  height: 33px;
  font-size: 13px;

  & > div {
    text-align: center;
  }

  border-bottom: 1px solid gainsboro;
  border-top: 1px solid gainsboro;
}

.header {
  background: gainsboro;

  & > td {
    word-break: break-word;
    background-color: #f8f8f9;
    color: #515a6e;
    height: 33px;
    font-size: 13px;
  }
}

.ImageList {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border: 1px solid gainsboro;

  & > div {
    text-align: center;
  }
}

.contrler {
  padding: 0 !important;
  background-color: white;
  box-shadow: 5px 0 5px -5px rgba(0, 0, 0, 1);
  /* 左侧边框阴影 */
  position: sticky;
  right: -20px;
  z-index: 2;
}

::v-deep .el-table__cell {
  padding: 0 !important;
}

.goods {
  &-img {
    &-box {
      position: relative;
    }

    &-mini {
      height: 24px;
      border-radius: 3px;

      &:hover {
        & + .goods-img-big {
          display: block;
        }
      }
    }

    &-big {
      // display: none;
      position: absolute;
      z-index: 100;
      top: -180px;
      left: 0;
      transform: translate(0, 70px);
      width: 200px;
      height: 200px;
      border-radius: 3px;
    }
  }
}

.bigImg {
  border-radius: 3px;
  z-index: 10;
  position: fixed;
  width: 200px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.parcel {
  ::v-deep .el-input__inner {
    border-radius: 5px 0 0 5px;
  }
}

.btnParcel {
  border-radius: 0 5px 5px 0;
}
</style>
